import json
import os

from common.common import exter_attack, output_result_file, output_execution_result_ex
from common.const import ParamConstant
from exchange.common.const import ExchangeSubType, ExchangeCode, ErrorCode, ExchangeQueryType
from exchange.common.exchange_exception import ErrCodeException
from exchange.handle.resource.resource_info import ExchangeResourceInfo
from exchange.logger import log


class ResourceAbility:
    @staticmethod
    @exter_attack
    def check_application(req_id, job_id, sub_id, data):
        result_path = os.path.join(ParamConstant.RESULT_PATH, f"result{req_id}")
        resource_info = ExchangeResourceInfo(req_id)
        body_err_code = ExchangeCode.SUCCESS.value
        err_code = ExchangeCode.SUCCESS.value
        err_msg = "Check connection success!"
        parameters = []
        try:
            resource_info.check_connectivity()
        except ErrCodeException as err_code_ex:
            err_code = ExchangeCode.FAILED.value
            body_err_code = err_code_ex.error_code
            err_msg = err_code_ex.error_message_json
            parameters = json.loads(err_msg).get("parameters")
        except Exception as ex:
            err_code = ExchangeCode.FAILED.value
            body_err_code = ErrorCode.ERR_INPUT_STRING
            err_msg = f"exception occurs. {ex}"
        finally:
            log.info(f"Check application end result is {err_msg}.")
            ResourceAbility.write_error_param_to_result_file(result_path, err_code, body_err_code, err_msg, parameters)

    @staticmethod
    @exter_attack
    def list_application_v2(req_id, job_id, sub_id, data):
        resource_info = ExchangeResourceInfo(req_id)
        information = resource_info.get_info()
        params = {"resourceInfo": information}
        log.info(f"req_id {req_id} params {params}")
        output_result_file(req_id, params)
        log.info(f"List_application_v2 success req:{req_id}.")

    @staticmethod
    def write_error_param_to_result_file(path: str, code: int, error_code: int, message: str, parameters):
        output_execution_result_ex(path, {"code": code, "bodyErr": error_code, "message": message,
                                          "bodyErrParams": parameters})
